<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="Content-Security-Policy" content="default-src * data: blob: 'unsafe-inline' 'unsafe-eval';">
    <title>敏感词加载测试</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            padding: 20px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            margin: 0;
        }
        .container {
            max-width: 600px;
            margin: 0 auto;
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(10px);
            border-radius: 20px;
            padding: 30px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
        }
        h1 {
            text-align: center;
            margin-bottom: 30px;
            font-size: 28px;
        }
        .test-item {
            background: rgba(255, 255, 255, 0.15);
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 15px;
            border-left: 4px solid transparent;
            transition: all 0.3s ease;
        }
        .test-item.success {
            border-left-color: #4ade80;
            background: rgba(74, 222, 128, 0.2);
        }
        .test-item.error {
            border-left-color: #f87171;
            background: rgba(248, 113, 113, 0.2);
        }
        .test-item.pending {
            border-left-color: #fbbf24;
            background: rgba(251, 191, 36, 0.2);
        }
        .test-title {
            font-size: 16px;
            font-weight: 600;
            margin-bottom: 10px;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .test-status {
            font-size: 24px;
        }
        .test-detail {
            font-size: 14px;
            opacity: 0.9;
            line-height: 1.6;
            margin-top: 10px;
            white-space: pre-wrap;
            word-break: break-all;
        }
        .test-button {
            width: 100%;
            padding: 15px;
            background: linear-gradient(135deg, #4ade80 0%, #3b82f6 100%);
            border: none;
            border-radius: 12px;
            color: white;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            margin-top: 20px;
            transition: transform 0.2s;
        }
        .test-button:active {
            transform: scale(0.98);
        }
        .test-button:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }
        .summary {
            text-align: center;
            margin-top: 30px;
            padding: 20px;
            background: rgba(255, 255, 255, 0.15);
            border-radius: 12px;
            font-size: 18px;
            font-weight: 600;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🔍 敏感词加载测试</h1>
        
        <div id="test1" class="test-item pending">
            <div class="test-title">
                <span class="test-status">⏳</span>
                <span>测试 1: 检测 WebView 环境</span>
            </div>
            <div class="test-detail">等待测试...</div>
        </div>

        <div id="test2" class="test-item pending">
            <div class="test-title">
                <span class="test-status">⏳</span>
                <span>测试 2: 检测文件路径</span>
            </div>
            <div class="test-detail">等待测试...</div>
        </div>

        <div id="test3" class="test-item pending">
            <div class="test-title">
                <span class="test-status">⏳</span>
                <span>测试 3: 加载 forbiddenWords.json</span>
            </div>
            <div class="test-detail">等待测试...</div>
        </div>

        <div id="test4" class="test-item pending">
            <div class="test-title">
                <span class="test-status">⏳</span>
                <span>测试 4: 验证敏感词数据</span>
            </div>
            <div class="test-detail">等待测试...</div>
        </div>

        <button id="runTestBtn" class="test-button" onclick="runAllTests()">
            🚀 运行所有测试
        </button>

        <div id="summary" class="summary" style="display: none;"></div>
    </div>

    <script>
        let testResults = {
            test1: false,
            test2: false,
            test3: false,
            test4: false
        };

        function updateTest(testId, status, statusEmoji, detail) {
            const testEl = document.getElementById(testId);
            testEl.className = `test-item ${status}`;
            testEl.querySelector('.test-status').textContent = statusEmoji;
            testEl.querySelector('.test-detail').textContent = detail;
            testResults[testId] = (status === 'success');
        }

        function showSummary() {
            const passedTests = Object.values(testResults).filter(r => r).length;
            const totalTests = Object.keys(testResults).length;
            const summaryEl = document.getElementById('summary');
            
            if (passedTests === totalTests) {
                summaryEl.innerHTML = `✅ 所有测试通过 (${passedTests}/${totalTests})`;
                summaryEl.style.background = 'rgba(74, 222, 128, 0.3)';
            } else {
                summaryEl.innerHTML = `⚠️ 部分测试失败 (${passedTests}/${totalTests} 通过)`;
                summaryEl.style.background = 'rgba(248, 113, 113, 0.3)';
            }
            summaryEl.style.display = 'block';
        }

        async function runAllTests() {
            const btn = document.getElementById('runTestBtn');
            btn.disabled = true;
            btn.textContent = '⏳ 测试中...';

            // 测试 1: 检测环境
            try {
                const userAgent = navigator.userAgent;
                const isAndroid = /Android/i.test(userAgent);
                const isIOS = /iPhone|iPad|iPod/i.test(userAgent);
                const currentURL = window.location.href;
                
                let detail = `User Agent: ${userAgent}\n`;
                detail += `平台: ${isAndroid ? 'Android' : isIOS ? 'iOS' : '其他'}\n`;
                detail += `当前URL: ${currentURL}\n`;
                detail += `协议: ${window.location.protocol}`;
                
                updateTest('test1', 'success', '✅', detail);
                console.log('✅ 测试1通过: 环境检测成功');
            } catch (error) {
                updateTest('test1', 'error', '❌', `错误: ${error.message}`);
                console.error('❌ 测试1失败:', error);
            }

            await new Promise(resolve => setTimeout(resolve, 500));

            // 测试 2: 检测文件路径
            try {
                const testPaths = [
                    './forbiddenWords.json',
                    'forbiddenWords.json',
                    '../ai-html/forbiddenWords.json'
                ];
                
                let detail = '测试以下路径:\n';
                testPaths.forEach(path => {
                    detail += `  - ${path}\n`;
                });
                detail += `\n推荐使用相对路径: ./forbiddenWords.json`;
                
                updateTest('test2', 'success', '✅', detail);
                console.log('✅ 测试2通过: 路径准备完成');
            } catch (error) {
                updateTest('test2', 'error', '❌', `错误: ${error.message}`);
                console.error('❌ 测试2失败:', error);
            }

            await new Promise(resolve => setTimeout(resolve, 500));

            // 测试 3: 加载 JSON 文件
            let forbiddenWordsData = null;
            try {
                console.log('🔍 开始加载 forbiddenWords.json...');
                const response = await fetch('./forbiddenWords.json');
                
                console.log('📡 Response status:', response.status);
                console.log('📡 Response ok:', response.ok);
                console.log('📡 Response type:', response.type);
                console.log('📡 Response url:', response.url);
                
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                
                forbiddenWordsData = await response.json();
                
                let detail = `✅ 加载成功!\n`;
                detail += `Status: ${response.status}\n`;
                detail += `Response URL: ${response.url}\n`;
                detail += `Content-Type: ${response.headers.get('content-type') || 'N/A'}`;
                
                updateTest('test3', 'success', '✅', detail);
                console.log('✅ 测试3通过: JSON文件加载成功');
            } catch (error) {
                let detail = `❌ 加载失败!\n\n`;
                detail += `错误类型: ${error.name}\n`;
                detail += `错误消息: ${error.message}\n\n`;
                
                if (error.message.includes('Failed to fetch')) {
                    detail += `可能原因:\n`;
                    detail += `1. WebView 未启用本地文件访问\n`;
                    detail += `2. 文件路径不正确\n`;
                    detail += `3. CORS 跨域限制\n`;
                    detail += `4. 文件不存在\n\n`;
                    detail += `请检查 controller.dart 中的配置:\n`;
                    detail += `- setAllowFileAccess(true)\n`;
                    detail += `- setAllowFileAccessFromFileURLs(true)\n`;
                    detail += `- setAllowUniversalAccessFromFileURLs(true)`;
                }
                
                updateTest('test3', 'error', '❌', detail);
                console.error('❌ 测试3失败:', error);
            }

            await new Promise(resolve => setTimeout(resolve, 500));

            // 测试 4: 验证数据
            if (forbiddenWordsData) {
                try {
                    if (!forbiddenWordsData.words || !Array.isArray(forbiddenWordsData.words)) {
                        throw new Error('数据格式错误: 缺少 words 数组');
                    }
                    
                    const wordCount = forbiddenWordsData.words.length;
                    const sampleWords = forbiddenWordsData.words.slice(0, 5);
                    
                    let detail = `✅ 数据验证通过!\n\n`;
                    detail += `敏感词总数: ${wordCount}\n\n`;
                    detail += `示例词汇 (前5个):\n`;
                    sampleWords.forEach((word, i) => {
                        detail += `  ${i + 1}. ${word}\n`;
                    });
                    
                    updateTest('test4', 'success', '✅', detail);
                    console.log('✅ 测试4通过: 数据验证成功');
                } catch (error) {
                    updateTest('test4', 'error', '❌', `错误: ${error.message}`);
                    console.error('❌ 测试4失败:', error);
                }
            } else {
                updateTest('test4', 'error', '❌', '无法验证: JSON 文件未加载');
                console.error('❌ 测试4失败: 数据为空');
            }

            btn.disabled = false;
            btn.textContent = '🔄 重新测试';
            
            showSummary();
        }

        // 页面加载完成后自动运行测试
        window.addEventListener('DOMContentLoaded', function() {
            console.log('📄 页面加载完成');
            // 延迟1秒后自动运行测试
            setTimeout(runAllTests, 1000);
        });

        // 通知 Flutter（如果需要）
        if (typeof Android !== 'undefined' && typeof Android.postMessage === 'function') {
            console.log('✅ Android 接口可用');
        } else if (typeof webkit !== 'undefined' && webkit.messageHandlers) {
            console.log('✅ iOS 接口可用');
        } else {
            console.log('⚠️ 原生接口不可用（可能在浏览器中测试）');
        }
    </script>
</body>
</html>

